import React, { Component } from 'react';
import styles from './style.scss';
import PropTypes from 'prop-types';

class RadioGroup extends Component {
    static propTypes = {
        defaultValue: PropTypes.any,
        value: PropTypes.any,
        name: PropTypes.string,
        onChange: PropTypes.func.isRequired
    };

    renderChildren() {
        const { defaultValue, value, name, onChange, children } = this.props;

        if (defaultValue && !value) {
            return React.Children.map(children, child => {
                return React.cloneElement(child, {
                    checked: defaultValue === child.props.value,
                    name,
                    onChange
                })
            });
        }

        return React.Children.map(children, child => {
            return React.cloneElement(child, {
                checked: value === child.props.value,
                name,
                onChange
            })
        });
    }

    render() {
        const { defaultValue, value, name, onChange, children, ...others } = this.props;
        return <div className={styles.radioGroup} {...others}>{this.renderChildren()}</div>;
    }
}

export default RadioGroup;